﻿using fuzhu;
using LH.Models.APAR;
using LH.U8API.Bus; 
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;
using LH.Model.SA;
using ZDEntity;
using XXX.Models.AS;
using System.Diagnostics.Eventing.Reader;
using XXX.Models.WDFT;
using System.DirectoryServices.ActiveDirectory;
using System.Reflection;
using System.Security.Cryptography;
using System.Xml.Linq;
using MySqlConnector;
using XXX.Models.XXXEntities;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore.Metadata;
using LH.Model.PU;
using Microsoft.VisualBasic;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class SaleOrderVM : SaleOrder
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public SaleOrderVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }


        /// <summary>
        /// 传入json转换成saleordervm
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public SaleOrderVM  GetAddEntity(API_SaleOrder obj, ref string cErr)
        {

            try
            { 
                
                if (string.IsNullOrWhiteSpace(obj.cSoCode))
                {
                    cErr = "销售订单号不能为空";
                    return null;
                } 
                if (string.IsNullOrWhiteSpace(obj.cSTCode))
                {
                    cErr = "销售类型不能为空";
                    return null;
                }
                if (string.IsNullOrWhiteSpace(obj.cDepCode))
                {
                    cErr = "销售部门不能为空";
                    return null;
                }
                if (string.IsNullOrWhiteSpace(obj.cExchName))
                {
                    cErr = "币种不能为空";
                    return null;
                }
                else if (obj.cExchName != "人民币" && string.IsNullOrWhiteSpace(obj.iExchrate))
                {
                    cErr = "外币单据，汇率不能为空";
                    return null;
                }
                else if (obj.cExchName=="人民币" &&   string.IsNullOrWhiteSpace(obj.iExchrate))
                {
                    obj.iExchrate ="1"; 
                }
                 
                 
                //检查客户编码是否存在
                CustomerVM customerVM = new CustomerVM();
                if (!customerVM.Exists(obj.cCusCode))
                {
                    cErr = $"U8中客户编码{obj.cCusCode}不存在";
                    return null; 
                }


                SaleOrder.Head head = new SaleOrder.Head
                {
                    csocode = obj.cSoCode, 
                    ddate = obj.dDate,
                    ccuscode = obj.cCusCode,
                    cdepcode = obj.cDepCode,
                    cpersoncode = obj.cPersonCode,
                    cmaker = obj.cMaker,
                    ccusoaddress = obj.cCusOAddress,
                    cgatheringplan = obj.cGatheringPlan,
                    dverifydate = obj.dVerifyDate,
                    cverifier = obj.cVerifier,
                    cmemo = obj.cMemo,
                    cexch_name = obj.cExchName,
                    iexchrate = obj.iExchrate , 
                    cstcode = obj.cSTCode,
                    cbustype = "普通销售",
                    ivtid = "95",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };

                 Decimal iTaxRate = 0.00m;

                List<SaleOrder.Body> bodies = new List<SaleOrder.Body>();

                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    int i = 0;
                    foreach (var item in obj.itemList)
                    {
                        if (string.IsNullOrWhiteSpace(item.cInvCode))
                        {
                            cErr = "存货编码不能为空";
                            return null;
                        }
                        if (item.iTaxRate != 0.00m)
                        {
                            iTaxRate = item.iTaxRate;
                        }
                        if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(item.dPreDate)))
                        {
                            cErr = "预计发货日期不能为空";
                            return null;
                        }
                        i++;
                        SaleOrder.Body body = new SaleOrder.Body
                        {

                            cinvcode = item.cInvCode,
                            //cfree1 = item.cFree1,
                            //cfree2 = item.cFree2,
                            //cfree3 = item.cFree3,
                            //cfree4 = item.cFree4,
                            irowno = item.iRowNo,
                            itaxrate = iTaxRate,
                            iquantity = item.iQuantity,
                            dpredate  = item.dPreDate.ToString("yyyy-MM-dd"),
                            dpremodate = item.dPreDate.ToString("yyyy-MM-dd"),
                            inum = DbHelper.GetDbdecimal(item.iNum),
                            isum = DbHelper.GetDbdecimal(item.iOriSum),
                            iquotedprice = DbHelper.GetDbdecimal(item.iNatTaxUnitPrice),
                            itaxunitprice = DbHelper.GetDbdecimal(item.iOriTaxUnitPrice),
                            iunitprice = DbHelper.GetDbdecimal(item.iOriUnitPrice),
                            imoney = DbHelper.GetDbdecimal(item.iOriMoney),
                            itax = DbHelper.GetDbdecimal(item.iOriTax),
                            inatunitprice = DbHelper.GetDbdecimal(item.iNatTaxUnitPrice),
                            inatmoney = Math.Round(DbHelper.GetDbdecimal(item.iOriMoney) * DbHelper.GetDbdecimal(head.iexchrate), 2),
                            inattax = Math.Round(DbHelper.GetDbdecimal(item.iOriTax) * DbHelper.GetDbdecimal(head.iexchrate), 2),
                            inatdiscount = DbHelper.GetDbString(Math.Round(DbHelper.GetDbdecimal(item.idiscount) * DbHelper.GetDbdecimal(head.iexchrate), 2)),
                            inatsum = Math.Round(DbHelper.GetDbdecimal(item.iOriSum) * DbHelper.GetDbdecimal(head.iexchrate), 2),
                            idiscount = item.idiscount,
                            citemcode = item.cItemCode,
                            citem_class = item.cItem_Class,

                            cmemo = item.cbMemo,
                            //dpremodate = head.ddate,
                            //dpredate = head.ddate,
                            //当前行id
                            cdefine31 = item.cRowId,
                            //从22 写到37
                            cdefine22 = item.cDefine22,
                            cdefine23 = item.cDefine23,
                            cdefine24 = item.cDefine24,
                            cdefine25 = item.cDefine25,
                            cdefine26 = item.cDefine26,
                            cdefine27 = item.cDefine27,
                            cdefine28 = item.cDefine28,
                            cdefine29 = item.cDefine29,
                            cdefine30 = item.cDefine30,
                            cdefine33 = item.cDefine33,
                            cdefine32 = item.cDefine32,

                            cdefine34 = item.cDefine34,
                            cdefine35 = item.cDefine35,
                            cdefine36 = item.cDefine36,
                            cdefine37 = item.cDefine37
                        };
                        bodies.Add(body);
                    }
                }
                SaleOrderVM model = new SaleOrderVM(head, bodies); 
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

             


        }

        /// <summary>
        /// 传入json转换成PuAppVouchVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public SaleOrderVM GetCodeEntity(API_SaleOrder obj, ref string cErr)
        {

            try
            {

                SaleOrder.Head head = new SaleOrder.Head();
                head.csocode = obj.cSoCode;
                List<SaleOrder.Body> bodies = new List<SaleOrder.Body>();

                SaleOrderVM model = new SaleOrderVM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }
        }

        public  RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject($"销售订单号{head.csocode}已存在");
                }


                string cRe = GetSaleOrderInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
                 
                if (!SO_SOCO.AddVerifySaleOrder(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                        db.Updateable<SO_SOMain>()
                  .SetColumns(u => new SO_SOMain()
                  {
                      dverifydate = dDate,
                      cVerifier = head.cmaker
                  })
                  .Where(u => u.ID == iid)
                  .ExecuteCommand();
                    }
                }
                //else
                //{

                //    if (!SO_SOCO.OperateSaleOrder(id, "verify", out err))
                //    {
                //        //审核失败，需要删除数据
                //        SO_SOCO.OperateSaleOrder(id, "delete", out _);
                //        return DBService.ReErrObject("审核失败：" + err); ;
                //    }
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        /// <summary>
        /// 销售订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前销售订单号已删除");
                }
                
                if (!SO_SOCO.OperateSaleOrder(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }
                //else
                //{
                //    if (!SO_SOCO.OperateSaleOrder(ID, "delete", out err))
                //    {
                //        //删除失败,重新审核，保持原样
                //        SO_SOCO.OperateSaleOrder(ID, "verify", out _);
                //        return DBService.ReErrObject("删除失败：" + err);
                //    }
                return DBService.ReOKObject(head.csocode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }


        /// <summary>
        /// 销售订单 变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2  Change()
        {
            try
            {
                string idcheck = "";
                if (!Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前销售订单号不存在");
                }

                head.id = idcheck;
                string cRe = GetSaleOrderInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
                head.editprop = "M";
                //增加变更人
                //head.cchanger = head.cmaker;
                //head.dmoddate = head.ddate;


                //变更的处理， （1） 主键id，子表isosid写入（2）判断是新增，还是修改，还是删除 （3）时间戳读取

               
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //取表头的时间戳
                    string sql = string.Format("select  cmaker,cverifier,  convert(char,convert(money,ufts),2) ufts from SO_SOMain where cSOCode = '{0}' ", head.csocode);
                    Head u8head = db.Ado.SqlQuery<Head>(sql).FirstOrDefault();

                    head.ufts = u8head.ufts;
                    //修改人更改
                    head.cchanger = head.cmaker;
                    head.cchangeverifier = head.cverifier;
                    head.dmoddate = DateTime.Now.ToString("yyyy-MM-dd");
                    head.dchangeverifydate = head.dmoddate;
                    head.cmaker = u8head.cmaker;
                    head.cverifier = u8head.cverifier;
                    head.id = idcheck;
                    //默认审核状态,没有勇
                    //head.istatus = "1";
                    //取表体信息,默认全部是D，循环后，剩余是D的，再写入表体
                    sql = string.Format("select 'D' AS editprop,  isosid,cdefine33, convert(char,convert(money,dufts),2) dufts  from SO_SODetails where id = '{0}' ", idcheck);

                    List<Body> u8bodies = db.Ado.SqlQuery<Body>(sql);
                    int bmodify = 0;//编辑标记
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        bodies[i].id = idcheck;
                        bmodify = 0;
                        for (int j = 0; j < u8bodies.Count; j++)
                        {
                            if (bodies[i].cdefine33==u8bodies[j].cdefine33)
                            {
                                //表体不需要时间戳
                                //bodies[i].dufts = u8bodies[j].dufts;
                                bodies[i].isosid = u8bodies[j].isosid;
                                bodies[i].editprop ="M";
                                u8bodies[j].editprop = "M";
                                bmodify = 1;
                                continue;
                            }
                        }
                        if(bmodify==0)
                        {
                            bodies[i].editprop = "A";
                        }

                    }
                    //循环后检查删除的
                    for (int j = 0; j < u8bodies.Count; j++)
                    {
                        if (u8bodies[j].editprop == "D")
                        {
                            Body body = new Body();
                            body.id = idcheck;
                            body.editprop = "D";
                            //body.dufts = u8bodies[j].dufts;
                            body.isosid = u8bodies[j].isosid;
                            bodies.Add(body);
                        }
                    }

                }

                string err = "";
                if (!SO_SOCO.ChangeSaleOrder(this, xmlConfig, out err, out string id, out string ccode))
                {
                     
                    return DBService.ReErrObject("变更失败：" + err);
                }
               
                return DBService.ReOKObject("变更完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 完善销售订单信息,处理客户，金额，税率，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetSaleOrderInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error:没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {


                string sqlFactory = "select top 1 cFactoryCode from Factory order by bDefaultFactory desc,cFactoryCode";
                string cFactoryCode = DbHelper.GetDbString(db.Ado.GetScalar(sqlFactory));



                Customer customer = db.Queryable<Customer>().Where(x => x.cCusCode == head.ccuscode).First();
                if (customer == null)
                {
                    return string.Format("Error:客户编码{0}不存在", head.ccuscode);
                }
                else
                {
                    head.ccusname = customer.cCusName;
                    head.cinvoicecompany = customer.cInvoiceCompany;
                }

                //#region  根据业务员取部门编码
                //if(!string.IsNullOrWhiteSpace(head.cpersoncode))
                //{
                //    Person person =db.Queryable<Person>().Where(x => x.cPersonCode == head.cpersoncode).First();
                //    if (person == null)
                //    {
                //        return string.Format("Error:业务员编码{0}不存在", head.cpersoncode);
                //    }
                //    else
                //    {
                //        head.cdepcode = person.cDepCode;                         
                //    }
                //}

                //#endregion

                for (int i = 0; i < bodies.Count; i++)
                {
                    string cInvCode = bodies[i].cinvcode;
                    

                    #region 处理辅助计量单位
                  

                    //如果igrouptype！=0，则需要获取辅助单位换算率，并计算辅助数量
                    InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode,"", "");
                    if (invProperty == null)
                    {
                        return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                    }
                    bodies[i].cgroupcode = invProperty.cGroupCode;
                    bodies[i].igrouptype = DbHelper.GetDbString(invProperty.iGroupType);
                    //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                    if (invProperty.iGroupType != "0")
                    {
                        //辅助计量单位来源于来源单据，如果没有取库存单位
                          bodies[i].cunitid = invProperty.cSTComUnitCode;
                          bodies[i].iinvexchrate = invProperty.iChangRate;
                        if ( string.IsNullOrEmpty(DbHelper.GetDbString(bodies[i].inum))  && DbHelper.GetDbdecimal(bodies[i].iinvexchrate) != 0)
                        {
                            bodies[i].inum = Math.Round(DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate), 6);

                        }
                          
                    }
                    
                    #endregion

                    #region 处理税率
                    //税率，先取客户档案，如果客户档案为空，币种是人民币的，默认税率是13

                    //if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].itaxrate)))
                    //{
                    //    if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(customer.iCusTaxRate)))
                    //    {
                    //        bodies[i].itaxrate = DbHelper.GetDbdecimal(customer.iCusTaxRate);
                    //    }
                    //    //else if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(inv.iTaxRate)))
                    //    //{
                    //    //    bodies[i].itaxrate = DbHelper.GetDbdecimal(inv.iTaxRate);
                    //    //}
                    //    else if (head.cexch_name == "人民币")
                    //    {
                    //        //币种是人民币的，默认税率是13
                    //        bodies[i].itaxrate = 13;
                    //    }
                    //    else
                    //    {
                    //        bodies[i].itaxrate = 0;
                    //    }

                    //    if (i == 0)
                    //    {
                    //        head.itaxrate = DbHelper.GetDbString(bodies[i].itaxrate);
                    //    }
                    //}

                    #endregion

                    #region 处理金额： 根据含税单价反算单价和无税单价
                    //decimal dNatSum = DbHelper.GetDbdecimal(bodies[i].inatsum);  //本币含税金额
                    //decimal dOriSum = DbHelper.GetDbdecimal(bodies[i].isum);     //原币含税金额
                    //bodies[i].inatmoney = DbHelper.GetDbdecimal((dNatSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100)).ToString("F2"));
                    //bodies[i].imoney = DbHelper.GetDbdecimal((dOriSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100)).ToString("F2"));
                    //bodies[i].inattax = dNatSum - bodies[i].inatmoney;
                    //bodies[i].itax = dOriSum - bodies[i].imoney;
                    //bodies[i].itaxunitprice = Math.Round(dNatSum / bodies[i].iquantity, 6);
                    //bodies[i].inatunitprice = Math.Round(bodies[i].inatmoney / bodies[i].iquantity, 6);
                    //bodies[i].iunitprice = Math.Round(bodies[i].imoney / bodies[i].iquantity, 6);
                    //bodies[i].iquotedprice = bodies[i].itaxunitprice;
                    //bodies[i].idiscount = "0";
                    //bodies[i].kl = "100";
                    //bodies[i].kl2 = "100";
                    //bodies[i].bsaleprice = "1";
                    //bodies[i].bgift = "0";
                    #endregion
                    bodies[i].cfactorycode = cFactoryCode;
                    FitemVM fitemVM = new FitemVM();

                    if (fitemVM.GetName(bodies[i].citem_class, bodies[i].citemcode, out string citem_cname, out string citemname) == "ok")
                    {
                        bodies[i].citem_cname = citem_cname;
                        bodies[i].citemname = citemname;
                    }


                }
            }
            
            return "ok";
        }

        /// <summary>
        /// 检查销售单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from SO_SOMain where cSOCode='{0}' ", head.csocode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

        /// <summary>
        /// 销售订单 执行查询
        /// </summary>
        /// <returns></returns>
        public RetModel2 GetJinDu(string cSoCode)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    string sql = string.Format("select cInvCode,cDefine33  as Bid ,iQuantity,iFHQuantity from  SO_Somain a, SO_SODetails  b where a.id =b.id and a.cSOCode = '{0}' ", cSoCode);
                    List<WDFT_SaleOrderJinDu.Item> lst = db.Ado.SqlQuery<WDFT_SaleOrderJinDu.Item>(sql);                   
                     if (lst.Count > 0)
                    {
                        WDFT_SaleOrderJinDu saleOrderJinDu = new WDFT_SaleOrderJinDu(cSoCode, lst);
                        return DBService.ReOKObject(saleOrderJinDu);
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到该单号的信息");
                    }
                }
                    
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }



        

    }
}
